﻿// -----------------------------------------------------------------------
// <copyright file="UpdateUserEmailCommandHandler.cs">
// Copyright (c) 2013 Andrey Veselov. All rights reserved.
// License:  Microsoft Public License (MS-PL)
// Contacts: http://andrey.moveax.com  andrey@moveax.com
// </copyright>
// -----------------------------------------------------------------------

namespace Moveax.DataAccess.Cqrs.Highway.EF.UnitTests.DataAccess.CommandHandlers.Users
{
	using System.Data.Entity;
	using System.Diagnostics.Contracts;
	using System.Threading;
	using System.Threading.Tasks;
	using Moveax.DataAccess.Cqrs.Highway.EF.UnitTests.DataAccess.Database.Dto;
	using Moveax.DataAccess.Cqrs.Highway.EF.UnitTests.Model.Commands.Users;

	internal class UpdateUserEmailCommandHandler : ICommandHandlerAsync<UpdateUserEmailCommand>
	{
		private readonly IRepository _repository;
		private readonly IDataSource _dataSource;

		public UpdateUserEmailCommandHandler(IRepository repository, IDataSource dataSource)
		{
			Contract.Requires(repository != null);
			Contract.Requires(dataSource != null);

			this._repository = repository;
			this._dataSource = dataSource;
		}

		public async Task ExecuteAsync(UpdateUserEmailCommand command, CancellationToken cancellationToken)
		{
			var user = await this._dataSource.Set<UserDto>()
				.FirstOrDefaultAsync(u => u.Id == command.Id, cancellationToken)
				.ConfigureAwait(false);

			if (user != null) {
				user.Email = command.Email;
				this._repository.Update(user);
			}
		}
	}
}